package com.jzqf.bluetooth.client

import android.content.Intent
import android.os.Bundle
import android.os.Process
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.jzqf.bluetooth.base.BaseActivity
import com.jzqf.bluetooth.databinding.ActivityClientBinding
import com.jzqf.bluetooth.event.EventMessage
import com.jzqf.bluetooth.server.BleService
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


class ClientActivity : BaseActivity<ActivityClientBinding>() {
    private val TAG = "【ClientActivity】"
    private var mItemResultAdapter: ItemResultAdapter? = null
    private var resultList = mutableListOf<String>()
    private val REQUEST_CODE_BLUE = 11001;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding.exitBtn.setOnClickListener {
            Process.killProcess(Process.myPid())
            System.exit(1)
        }
        initResult()
        EventBus.getDefault().register(this)
    }

    override fun onStart() {
        super.onStart()
        //BLE客户端服务
        startService(Intent(this, BleClientService::class.java))
//        val intent = Intent(this, BleService::class.java)
//        intent.putExtra("number", 2)
//        startService(intent)
        //扫描蓝牙广播
//        BleUtil.initBleBluetooth(this)
//        BleUtil.startScanLe()
    }

    private fun initResult() {
        mViewBinding.clientRcv.layoutManager = LinearLayoutManager(this)
        mItemResultAdapter = ItemResultAdapter()
        mViewBinding.clientRcv.adapter = mItemResultAdapter
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        Log.d(TAG, "isFinish=${this.isFinishing}  ${this.isTaskRoot}")
    }

    override fun getViewBinding(): ActivityClientBinding {
        return ActivityClientBinding.inflate(layoutInflater)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_BLUE -> {
                resultList.add("设备已开启蓝牙并开启扫描")
                runOnUiThread {
                    mItemResultAdapter?.notifyData(resultList)
                    BleUtil.startScan()
                }

            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventReceiveMain(eventMessage: EventMessage) {
        mViewBinding.resultTv.setText(eventMessage.message)
    }


}